package test;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JOptionPane;

public class MyThread extends Thread {
	Socket socket;
	boolean an = false;
	TrayIcon trayIcon;
	SystemTray tray;
	String key = "0";
	String serverName = "";
	JButton buttonCall,buttonHide,buttoNewMess;
	boolean displayNewMess = false;

	ChatterWindows chatterWindows;

	public MyThread(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		try {
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(socket.getInputStream(), "UTF-8"));
			final PrintWriter printWriter = new PrintWriter(
					new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
			printWriter.println("Kết nối thành công");
			printWriter.flush();


			String testData= MaHoa.maHoa(key, "0123456789");
			printWriter.println(testData);
			printWriter.flush();


			String respone = bufferedReader.readLine();

			if(respone.equals("WRONG5482613483156748")){
				System.out.println("thoat server");
				return;
			}


			// chuyển tên cho client
			printWriter.println(serverName);
			printWriter.flush();


			// nhận tên từ server
			String name = bufferedReader.readLine();





//			final JFrame frame = new JFrame("server to " + name);
//			Container container = frame.getContentPane();
//			textView = new JTextArea();
//		  textData = new JTextField();
//			textView.setFont(new Font("Times New Roman", 0, 14));
//			JScrollPane scrollPane = new JScrollPane(textView);
//			scrollPane.setAutoscrolls(true);
//			container.add(scrollPane);
//			container.add(textData, BorderLayout.SOUTH);

			chatterWindows = new ChatterWindows("server "+Const.VERSION+" to " + name, key);
			chatterWindows.name = name;
			chatterWindows.myName = serverName;
			chatterWindows.panelPic.setName(name);
			chatterWindows.addWindowFocusListener(new WindowFocusListener() {

				@Override
				public void windowLostFocus(WindowEvent e) {
					printWriter.println("lofo2484534498756");
					printWriter.flush();

				}

				@Override
				public void windowGainedFocus(WindowEvent e) {
					printWriter.println("focs875548915464");
					printWriter.flush();

				}
			});




//			imageRead = Toolkit.getDefaultToolkit().getImage(Test1.class.getResource("/test/reading.png"));
//			imageWaitting = Toolkit.getDefaultToolkit().getImage(Test1.class.getResource("/test/waiting.png"));
//			panelRead = new PanelPic(imageRead);


//			textView.setLayout(null);
//			textView.add(panelRead);
//			panelRead.setBounds(400, 5, 64, 64);
//			panelRead.setBackground(Color.white);


			chatterWindows.textFieldSend.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					String a = chatterWindows.textFieldSend.getText();
					a = MaHoa.maHoa(key, a);
					printWriter.println(a);
					printWriter.flush();
					chatterWindows.textAreaView.setText(chatterWindows.textAreaView.getText() + "\n "+chatterWindows.myName+"("+Chatter_Util.getCurrentTime()+"): "
							+ chatterWindows.textFieldSend.getText());
					chatterWindows.textFieldSend.setText("");
					displayNewMess = false;
					chatterWindows.newMess(false);
					if (chatterWindows.buttonNewMess.isEnabled()) {// button new message (letter) is  enable => người kia ko đọc
						chatterWindows.lblReadAlready.setText("Chưa đọc");
					}

				}
			});

			chatterWindows.textFieldSend.addKeyListener(new KeyAdapter() {

				@Override
				public void keyPressed(KeyEvent e) {
					super.keyPressed(e);
					//System.out.println(e.getKeyCode());
					if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
						System.out.println("hide");
						MyThread.this.chatterWindows.setVisible(false);
					}

				}

				@Override
				public void keyReleased(KeyEvent e) {
					// TODO Auto-generated method stub
					super.keyReleased(e);
					if(MyThread.this.chatterWindows.checkTempView.isSelected()) {
						String content = chatterWindows.textFieldSend.getText();
						content = MaHoa.maHoa(key, content);
						content = ChatterWindows.TEMP_VIEW_STRING + content;
						printWriter.println(content);
						printWriter.flush();
					}
				}



			});
			chatterWindows.textAreaView.setText("welcome...");

			trayIcon = null;
			if (SystemTray.isSupported()) {

				tray = SystemTray.getSystemTray();
				Image image = Toolkit.getDefaultToolkit().getImage(
						RunServer.class.getResource("/test/s.png"));

				MouseListener mouseListener = new MouseListener() {

					public void mouseClicked(MouseEvent e) {
					}

					public void mouseEntered(MouseEvent e) {
					}

					public void mouseExited(MouseEvent e) {
					}

					public void mousePressed(MouseEvent e) {
					}

					public void mouseReleased(MouseEvent e) {
					}
				};

				ActionListener exitListener = new ActionListener() {
					public void actionPerformed(ActionEvent e) {

						try {

							socket.close();
							tray.remove(trayIcon);
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
				};

				PopupMenu popup = new PopupMenu();
				MenuItem defaultItem = new MenuItem("Exit");
				defaultItem.addActionListener(exitListener);
				popup.add(defaultItem);

				trayIcon = new TrayIcon(image, "Nhan chatter", popup);
				trayIcon.setToolTip("Nhan_chatter_server to "+name);

				ActionListener actionListener = new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						chatterWindows.setVisible(true);
						an = false;

					}
				};
				trayIcon.addMouseListener(new MouseListener() {

					@Override
					public void mouseReleased(MouseEvent e) {
						// TODO Auto-generated method stub

					}

					@Override
					public void mousePressed(MouseEvent e) {
						// TODO Auto-generated method stub

					}

					@Override
					public void mouseExited(MouseEvent e) {
						// TODO Auto-generated method stub

					}

					@Override
					public void mouseEntered(MouseEvent e) {
						// TODO Auto-generated method stub

					}

					@Override
					public void mouseClicked(MouseEvent e) {
						int count = e.getClickCount();
						if (count == 2) {
							chatterWindows.setVisible(true);
							an = false;
						}

					}
				});

				trayIcon.setImageAutoSize(true);
				trayIcon.addActionListener(actionListener);
				trayIcon.addMouseListener(mouseListener);

				try {
					tray.add(trayIcon);
				} catch (AWTException e) {
					System.err.println("TrayIcon could not be added.");
				}

			} else {

				// System Tray is not supported

			}

			chatterWindows.buttonHide.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					chatterWindows.setVisible(false);
					an = true;

				}
			});
			chatterWindows.buttonCall.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					printWriter.println("call75315987412369");
					printWriter.flush();

				}
			});
			chatterWindows.buttonNewMess.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					printWriter.println("new56474456488948");
					printWriter.flush();
					chatterWindows.textFieldSend.setFocusable(true);

				}
			});


			ThreadServerRead threadS = new ThreadServerRead(
					bufferedReader, socket, chatterWindows, this);
			threadS.start();
			chatterWindows.addWindowListener(new WindowListener() {

				@Override
				public void windowOpened(WindowEvent e) {
					// TODO Auto-generated method stub

				}

				@Override
				public void windowIconified(WindowEvent e) {
					// TODO Auto-generated method stub

				}

				@Override
				public void windowDeiconified(WindowEvent e) {
					// TODO Auto-generated method stub

				}

				@Override
				public void windowDeactivated(WindowEvent e) {
					// TODO Auto-generated method stub

				}

				@Override
				public void windowClosing(WindowEvent e) {
					int y = JOptionPane.showConfirmDialog(chatterWindows, "Bạn muốn thoát phải không ?", "Exist ? ", JOptionPane.YES_NO_OPTION);
					if(y == JOptionPane.NO_OPTION){
						return;
					}
					if (!socket.isClosed()) {
						try {
							socket.close();
							tray.remove(trayIcon);
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
					chatterWindows.setVisible(false);

				}

				@Override
				public void windowClosed(WindowEvent e) {
					// TODO Auto-generated method stub

				}

				@Override
				public void windowActivated(WindowEvent e) {
					// TODO Auto-generated method stub

				}
			});
			chatterWindows.setVisible(true);
			chatterWindows.textFieldSend.requestFocus();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


	}

}
